package xormx

import (
	"database/sql"
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

func Group() {
	conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",  // first one is master
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;", // slave
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",  // slave
	}
	eg, _ := xorm.NewEngineGroup("postgres", conns)
	fmt.Println(eg.Close())
}

func balancePolicy() {
	conns := []string{
		"postgres://postgres:root@localhost:5432/test?sslmode=disable;",  // first one is master
		"postgres://postgres:root@localhost:5432/test1?sslmode=disable;", // slave
		"postgres://postgres:root@localhost:5432/test2?sslmode=disable",  // slave
	}
	//eg, _ := xorm.NewEngineGroup("postgres", conns)
	eg, _ := xorm.NewEngineGroup("postgres", conns, xorm.WeightRandomPolicy([]int{2, 3}))
	eg, _ = xorm.NewEngineGroup("postgres", conns, xorm.RoundRobinPolicy())
	eg, _ = xorm.NewEngineGroup("postgres", conns, xorm.LeastConnPolicy())
	fmt.Println(eg.Close())
}

func GetEngine(dsn string) (*xorm.Engine, error) {
	engine, err := xorm.NewEngine("mysql", dsn, func(db *sql.DB) error {
		db.SetMaxIdleConns(1 << 10)
		db.SetMaxOpenConns(1 << 10)

		return nil
	})
	if err != nil {
		return nil, err
	}

	f, err := os.Create("sql.log")
	if err != nil {
		return nil, err
	}

	engine.SetLogger(log.NewSimpleLogger(f))

	return engine, nil
}
